import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jyofservice/bean/diao_du_list_entity.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/gongdandiaodu/RightEndDrawer.dart';
import 'package:jyofservice/gongdanchaxun/RightDrawer.dart';
import 'package:jyofservice/util/DiaoDuNotification.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:jyofservice/gongdandiaodu/DiaoDuDetail.dart';

class GongDanDiaoDuPage extends StatefulWidget {
  String? view;
  String? title;

  GongDanDiaoDuPage({this.view, this.title});

  @override
  _GongDanDiaoDuPageState createState() => _GongDanDiaoDuPageState();
}

class _GongDanDiaoDuPageState extends State<GongDanDiaoDuPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  ScrollController scrollController = ScrollController();
  List<DiaoDuListData?> diaoduListData = [];
  int page = 1;
  String? wherestr = "1=1";
  bool isloading = false;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    diaoduListData.clear();
    getDiaoDuListData();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        print('滑动到了最底部');
        page++;
        getDiaoDuListData();
      }
    });

    //如果是工单调度和我的工单 不查询工单退回后状态为待下发的工单
    //如果是工单调度 只显示待指派
    if(widget.view=='GetMySelfWaitDoWorkConfirm') {
      wherestr = wherestr!+" and StateName!='待下发'";
    } else if(widget.view=='GetMyAndChildrenWorkForm'){
      wherestr = wherestr!+" and StateName!='待下发' and State=2";
    }
  }

  @override
  Widget build(BuildContext context) {
    return NotificationListener<DiaoDuNotification>(
      onNotification: (notification) {
        isloading = false;
        if (mounted) {
          setState(() {
            diaoduListData.clear();
            page = 1;
            wherestr = notification.wherestr;
            //如果是工单调度和我的工单 不查询工单退回后状态为待下发的工单
            //如果是工单调度 只显示待指派
            if(widget.view=='GetMySelfWaitDoWorkConfirm') {
              wherestr = wherestr!+" and StateName!='待下发'";
            } else if(widget.view=='GetMyAndChildrenWorkForm'){
              wherestr = wherestr!+" and StateName!='待下发' and State=2";
            }
            getDiaoDuListData();
          });
        }
        return true;
      },
      child: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          centerTitle: true,
          title: Text('${widget.title.toString()}',
              //FluroConvertUtils.fluroCnParamsDecode(widget.title),
              style: TextStyle(
                  color: Colors.white, fontSize: ScreenUtil().setSp(45))),
          leading: IconButton(
              icon: Icon(Icons.arrow_back_ios),
              onPressed: () {
                Navigator.pop(context, false);
              }),
          actions: <Widget>[
            IconButton(
              onPressed: () {
                _scaffoldKey.currentState!.openEndDrawer();
              },
              icon: Icon(
                Icons.list,
                color: Colors.white,
              ),
            ),
          ],
        ),
        body: Container(
          color: const Color(0xFFF1F1F1),
          child: Stack(
            alignment: Alignment(0.5, 0.5),
            children: <Widget>[
              RefreshIndicator(
                  child: ListView.builder(
                    physics: AlwaysScrollableScrollPhysics(),
                    controller: scrollController,
                    itemBuilder: (context, item) {
                      String isreadstr="";
                      if(diaoduListData[item]!.isRead==1) {
                        isreadstr = "已读";
                      }else{
                        isreadstr = "未读";
                      }
                      return buildListData(
                          context,
                          diaoduListData[item]!.createUserName,
                          diaoduListData[item]!.doUserName,
                          diaoduListData[item]!.createDate!,
                          diaoduListData[item]!.describe,
                          diaoduListData[item]!.stateName,
                          diaoduListData[item]!.ifyq,
                          diaoduListData[item]!.gdTypeId,
                          diaoduListData[item]!.typeName!,
                          diaoduListData[item]!.lSH,
                          diaoduListData[item]!.allName,isreadstr,diaoduListData[item]!.confirmState,
                          diaoduListData[item]!.isjdyq!,diaoduListData[item]!.jdsx_time,
                      );
                    },
                    itemCount: diaoduListData.length,
                  ),
                  onRefresh: _onRefresh),
              Offstage(
                offstage: isloading,
                child: SpinKitFadingCircle(
                  color: Colors.blue,
                  size: 50.0,
                ),
              )
            ],
          ),
        ),
        endDrawer: _getRightDrawer(),
      ),
    );
  }

  _getRightDrawer() {
    if (widget.view == "GetMyAndChildrenAllWorkForm" ||
        widget.view == "GetMyAllFinishWork") {
      return RightDrawer();
    } else {
      return RightEndDrawer();
    }
  }

  Widget buildListData(
      BuildContext context,
      String? xiafa,
      String? dousername,
      String createDate,
      String? describe,
      String? stateName,
      String? ifyq,
      int? typeid,
      String typeName,
      String? lsh,
      String? allName, String isRead,int? confirmstate,String isjdyq,String? jdsx_time) {
    return GestureDetector(
      child: Stack(
        alignment: Alignment(0.9, -0.9),
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(top: 11),
            color: Colors.white,
            width: ScreenUtil().screenWidth,
            // height: ScreenUtil().setHeight(380),
            child: Row(
              children: <Widget>[
                Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    Image.asset(
                      'images/juxing2kaobei24.png',
                      fit: BoxFit.fill,
                      width: ScreenUtil().setWidth(160),
                      height: ScreenUtil().setHeight(420),
                    ),
                    Text(
                      getTypeName(typeName),
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: ScreenUtil().setSp(40)),
                    ),
                  ],
                ),
                Expanded(
                  flex: 1,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Offstage(
                        offstage:
                        widget.view == "GetMySelfWaitDoWorkConfirm" ? false : true,
                        child: Padding(
                          padding: EdgeInsets.all(5),
                          child: Text(
                            '[' + isRead+"]",
                            style: TextStyle(
                                fontSize: ScreenUtil().setSp(32),
                                color: isRead=="已读"?Colors.green:Colors.red),
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.all(5),
                        child: Text(
                          '下单时间:' + createDate ?? "",
                          style: TextStyle(
                              fontSize: ScreenUtil().setSp(32),
                              color: Colors.black87),
                        ),
                      ),
                      Offstage(
                        offstage: jdsx_time == null?true:false,
                        child: Padding(
                          padding: EdgeInsets.all(5),
                          child: Row(
                            children: [
                              Text(
                                '接单时限:${jdsx_time == null ? "":jdsx_time+"小时"}',
                                style: TextStyle(
                                    fontSize: ScreenUtil().setSp(32),
                                    color: Colors.black87),
                              ),
                              SizedBox(width: 20,),
                              Text(
                                '是否超时:' + isjdyq ?? "",
                                style: TextStyle(
                                    fontSize: ScreenUtil().setSp(32),
                                    color: isjdyq=='是'?Colors.redAccent:Colors.black87),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Row(
                        children: [
                          Expanded(child: Column(
                            children: [
                              Row(
                                children: <Widget>[
                                  Padding(
                                    padding: EdgeInsets.fromLTRB(5, 5, 0, 5),
                                    child: Text(
                                      '处理人员:',
                                      style: TextStyle(
                                          fontSize: ScreenUtil().setSp(32),
                                          color: Colors.black87),
                                    ),
                                  ),
                                  Expanded(
                                    child: Padding(
                                      padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
                                      child: Text(
                                        '$dousername',
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                            fontSize: ScreenUtil().setSp(32),
                                            color: Colors.black87),
                                      ),
                                    ),
                                  )
                                ],
                              ),
                              ],
                          )),
                          // Padding(
                          //   padding: const EdgeInsets.only(right: 10),
                          //   child: Image.asset(stateName == '已处理' ? 'images/chulijieshu.png':confirmstate==1?'images/chulizhong.png':'images/weijiedan.png'),
                          // ),
                        ],
                      ),
                      Row(
                        children: <Widget>[
                          Padding(
                            padding: EdgeInsets.fromLTRB(5, 5, 0, 5),
                            child: Text(
                              '住户地址:',
                              style: TextStyle(
                                  fontSize: ScreenUtil().setSp(32),
                                  color: Colors.black87),
                            ),
                          ),
                          Expanded(
                            child: Padding(
                              padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
                              child: Text(
                                '$allName',
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: ScreenUtil().setSp(32),
                                    color: Colors.black87),
                              ),
                            ),
                          )
                        ],
                      ),
                      Container(
                        width: ScreenUtil().screenWidth,
                        height: ScreenUtil().setHeight(2),
                        color: Colors.grey,
                      ),
                      SizedBox(
                        height: ScreenUtil().setHeight(30),
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Expanded(
                              flex: 1,
                              child: Padding(
                                padding: EdgeInsets.only(left: 5),
                                child: Text(
                                  describe ?? "",
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                      color: stateName == "处理中"
                                          ? Colors.blue
                                          : stateName == "未接单"? Colors.red : Colors.green,
                                      fontSize: ScreenUtil().setSp(40),
                                      fontWeight: FontWeight.bold),
                                ),
                              )),
                          Image.asset(
                            stateName == "处理中"
                                ? 'images/daichuli.png'
                                : stateName == "未接单"?'images/weijiedan.png' : 'images/yichulikaobei.png',
                            width: ScreenUtil().setWidth(45),
                          ),
                          Padding(
                            padding: EdgeInsets.only(right: 5),
                            child: Text(
                              stateName??"",
                              style: TextStyle(
                                color: stateName == "处理中"
                                    ? Colors.blue
                                    : stateName == "未接单"? Colors.red : Colors.green,
                                fontSize: ScreenUtil().setSp(35),
                              ),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: ScreenUtil().setHeight(10),
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
          Offstage(
            offstage: ifyq == "是" ? false : true,
            child: Image.asset(
              'images/yuqi.png',
              width: ScreenUtil().setWidth(70),
            ),
          )
        ],
      ),
      onTap: () {
        bool is0ffstage = false;
        if (widget.view == "GetMyAndChildrenAllWorkForm" ||
            widget.view == "GetMyAllFinishWork") {
          is0ffstage = true;
        } else {
          is0ffstage = false;
        }
        print(("bool:" + is0ffstage.toString()));
        Navigator.push(context, new MaterialPageRoute(builder: (context) {
          return DiaoDuDetail(
            LSH: lsh,
            is0ffstage: is0ffstage,
            view: widget.view,
            isDeliver: false,
            //是否接单超时 是和否
            isjdyq: isjdyq,
            //接单时限
            jdsxTime:jdsx_time

          );
        })).then((data) {
          diaoduListData.clear();
          getDiaoDuListData();
        });
//        NavigatorUtil.goDiaoDuDetail(context, lsh, is0ffstage, widget.view);
      },
    );
  }

  String getTypeName(String typeName) {
    String result = "";

    for (int i = 0; i < typeName.length; i++) {
      if (i != typeName.length - 1) {
        String str = typeName.substring(i, i + 1);
        result += str + "\n";
      } else {
        String str = typeName.substring(i, i + 1);
        result += str;
      }
    }
    return result;
  }

  //刷新
  Future _onRefresh() async {
    page = 1;
    diaoduListData.clear();
    wherestr = "1=1";
    //如果是工单调度和我的工单 不查询工单退回后状态为待下发的工单
    //如果是工单调度 只显示待指派
    if(widget.view=='GetMySelfWaitDoWorkConfirm') {
      wherestr = wherestr!+" and StateName!='待下发'";
    } else if(widget.view=='GetMyAndChildrenWorkForm'){
      wherestr = wherestr!+" and StateName!='待下发' and State=2";
    }
    getDiaoDuListData().then((value) => {
      Fluttertoast.showToast(msg: '下拉刷新成功')
    });
  }

  //获取调度列表数据
  Future getDiaoDuListData() async {
//    showDialog(
//        context: context,
//        barrierDismissible: false,
//        builder: (BuildContext context) {
//          return LoadingDialog(
//            text: "正在加载数据…",
//          );
//        });
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "view": widget.view,
      "wherestr": wherestr,
      "limit": 10,
      "page": page,
      "sortName": "CreateDate",
      "sortOrder": widget.title =='工单查询'? "desc" : "asc",
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());

    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/postrowdataforlayui",
        data: data);
    print(response.data.toString());

    if (response.data["code"] == 0) {
      if(response.data["data"].length>0){
        for (int i = 0; i < response.data["data"].length; i++) {
          DiaoDuListData? diaoDuListEntity =
          new DiaoDuListData().fromJson(response.data["data"][i]);
          diaoduListData.add(diaoDuListEntity);
        }

      } else {
        //上拉加载更多
        if(page>1){
          page--;
          Fluttertoast.showToast(msg: "没有更多数据了");
        }else{
          Fluttertoast.showToast(msg: "未查询到数据");
        }

      }

      isloading = true;
      if (mounted) {
        setState(() {});
      }
    } else {
      Fluttertoast.showToast(msg: "当前请求数据错误请重新刷新");
    }
  }


}
